package com.webchartserver.core.utils;

import cn.hutool.core.collection.ConcurrentHashSet;
import org.springframework.stereotype.Component;

import java.io.*;

/**
 * 敏感信息过滤
 * 2023/4/18
 */
@Component
public class FilterWordsUtil {

    private FilterWordsUtil(){}

    // 敏感词汇集合
    private static ConcurrentHashSet<String> wordsSet = new ConcurrentHashSet<>();

    // 初始化加载敏感词汇
    static{
        System.out.println("------------敏感词汇过滤工具加载-------------------");
        loadTextFile();
    }

    /**
     * 加载敏感词汇文件
     */
    private static void loadTextFile(){
        try {

            InputStream resourceAsStream = FilterWordsUtil.class.getResourceAsStream("filterword.txt");

            Reader reader = new InputStreamReader(resourceAsStream);

            BufferedReader bufferedReader = new BufferedReader(reader);

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                wordsSet.add(line);
            }

            bufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 替换敏感字符
     * @param words 原字符串
     * @param replaceStr 替换的文本
     * @return
     */
    public static String changeWord(String words,char replaceStr){

        for(String mgStr:wordsSet){
            if(words.indexOf(mgStr)!=-1){

                // 根据敏感词的长度生成*
                int length = mgStr.length();
                String repStr = "";
                for(int i=0;i<length;i++){
                    repStr += replaceStr;
                }

                words = words.replaceAll(mgStr,repStr);
            }
        }

        return words;
    }

}
